import axios from "../request/axios";
import {
  Space,
  Table,
  Button,
  Modal,
  ConfigProvider,
  theme,
  message,
  //   Checkbox,
  Select,
  //   tag,
  TreeSelect,
  Form,
  Input,
  Popconfirm,
} from "antd";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import type {
  TableProps,
  PopconfirmProps,
  FormProps,
  TreeSelectProps,
} from "antd";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { useEffect, useState } from "react";
import { marked } from "marked";
function UseList() {
  const [bg, setBg] = useState([]);
  const [ys, setYs] = useState(false);
  const [ck, setCk] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [title, setTitle] = useState("");
  const [editId, setEditId] = useState([]);
  const [keyword, setKeyword] = useState("");
  const getData = (page: number, keyword: string, pageSize: number) => {
    axios
      .get("http://blogapi.shbwyz.com/article/list", {
        params: { page, pageSize, keyword },
      })
      .then((res) => {
        // console.log(res);
        setBg(res.data.rows);
        setTotal(res.data.count);
      });
  };
  useEffect(() => {
    getData(page, pageSize);
  }, []);
  const columns: TableProps["columns"] = [
    {
      title: "title",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "起始日期",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "content",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "结束日期",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },
    // {
    //     title: 'Tags',
    //     key: 'comments',
    //     dataIndex: 'comments',
    //     render: (_, { tags }) => (
    //       <>
    //         {tags.map((tag) => {
    //           let color = tag.length > 5 ? 'geekblue' : 'green';
    //           if (tag === 'loser') {
    //             color = 'volcano';
    //           }
    //           return (
    //             <Tag color={color} key={tag}>
    //               {tag.toUpperCase()}
    //             </Tag>
    //           );
    //         })}
    //       </>
    //     ),
    //   },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm
            title="删除确认框"
            description="你确定要删除吗?"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
          <Button onClick={() => showModal1(record.id)}>查看</Button>
          <Button
            onClick={() =>
              showModal(setTitle("编辑文章"), setEditId(record.id))
            }
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];
  //   换皮肤
  const fh = () => {
    setYs(!ys);
  };
  const fenye = (page: number, pageSize: number) => {
    setPage(1);
    setPageSize(10);
    getData(page, pageSize);
  };
  //删除成功
  const confirm: PopconfirmProps["onConfirm"] = (id) => {
    message.success("Click on Yes");
    axios.delete(`http://blogapi.shbwyz.com/article/${id}`).then((res) => {
      console.log(res);
      message.success("删除成功");
      getData();
    });
  };
  //取消删除
  const cancel: PopconfirmProps["onCancel"] = (e) => {
    console.log(e);
    message.error("Click on No");
  };
  const [isModalOpen1, setIsModalOpen1] = useState(false);
  // 查看弹窗
  const showModal1 = (id: number) => {
    setIsModalOpen1(true);
    axios.get(`http://blogapi.shbwyz.com/article/${id}`).then((res) => {
      //   console.log(res);
      setCk(res.data);
    });
  };
  // 查看确认关闭弹窗
  const handleOk1 = () => {
    setIsModalOpen1(false);
  };
  // 查看取消关闭弹窗
  const handleCancel1 = () => {
    setIsModalOpen1(false);
  };
  // 新增编辑弹窗
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // -------------------------------------------------------------------
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法

  // 编辑器内容
  const [html, setHtml] = useState("<p>hello</p>");

  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    setTimeout(() => {
      setHtml("<p>hello world</p>");
    }, 1500);
  }, []);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // const toolbarConfig = { }                        // JS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: "请输入内容...",
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  // -------------------------------------------------------------------
  const onFinish: FormProps["onFinish"] = (values) => {
    console.log("Success:", values);
    if (title === "新增文章") {
      axios({
        method: "post",
        url: "http://blogapi.shbwyz.com/article",
        data: {
          title: values.title,
          content: html,
          authorId: 47529555,
        },
      }).then((res) => {
        console.log(res);
        getData();
        setIsModalOpen(false);
      });
    } else {
      axios({
        method: "put",
        url: `http://blogapi.shbwyz.com/article/${editId}`,
        data: {
          title: values.title,
          content: html,
          authorId: 47529555,
        },
      }).then((res) => {
        console.log(res);
        getData();
        setIsModalOpen(false);
      });
    }
  };

  const onFinishFailed: FormProps["onFinishFailed"] = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  //  搜索
  const onFinish1: FormProps["onFinish"] = (values) => {
    console.log("Success:", values);
    setKeyword(values.username);
    getData(1, values.username, pageSize);
  };
  return (
    <ConfigProvider
      theme={{
        algorithm: ys ? theme.darkAlgorithm : theme.compactAlgorithm,
      }}
    >
      <div>
        <Button style={{ margin: "10px" }} onClick={fh}>
          换肤
        </Button>
        <Button
          style={{ margin: "10px" }}
          type="primary"
          onClick={() => showModal(setTitle("新增文章"))}
        >
          新增
        </Button>
        {/* ----------------------------------------------------查找-----------------------------------------------------  */}
        <Form onFinish={onFinish1}>
          <Form.Item name="username">
            <Input style={{ width: 200 }} placeholder="请输入文章标题" />
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              点击搜索
            </Button>
          </Form.Item>
        </Form>
        {/* ----------------------------------------------------查找-----------------------------------------------------  */}
        <Table
          columns={columns}
          dataSource={bg}
          pagination={{
            total: total,
            current: page,
            pageSize: pageSize,
            onChange: fenye,
          }}
        />
        {/* 查看弹窗 */}
        <Modal
          title="查看框"
          open={isModalOpen1}
          onOk={handleOk1}
          onCancel={handleCancel1}
        >
          <div
            dangerouslySetInnerHTML={{ __html: marked(ck.content || "") }}
          ></div>
        </Modal>
        {/* 新增编辑弹窗 */}
        <Modal
          title={title}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item label="title" name="title">
              <Input />
            </Form.Item>

            <Form.Item label="起始日期" name="createdAt">
              <Select>
                <Select.Option>2025-1-18</Select.Option>
                <Select.Option>2025-2-18</Select.Option>
                <Select.Option>2025-3-18</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item label="content" name="content">
              <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                style={{ borderBottom: "1px solid #ccc" }}
              />
              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={(editor) => setHtml(editor.getHtml())}
                mode="default"
                style={{ height: "500px", overflowY: "hidden" }}
              />
            </Form.Item>

            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                +New Tag
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </ConfigProvider>
  );
}

export default UseList;
